package com.crm.sys.push;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;

import com.google.gson.Gson;
import com.crm.im.core.model.Message;
import com.crm.im.core.push.IMMessagePusher;
import com.crm.im.core.session.DefaultSessionManager;
import com.crm.im.core.session.IMSession;
import com.crm.im.core.websocket.SpringWebSocketHandler;
import com.crm.sys.dao.SysMessageDao;



/**
 * 消息发送实现类
 * 
 */
@Service("messagePusher")
public class DefaultMessagePusher implements  IMMessagePusher {


	private final Log log = LogFactory.getLog(getClass());
	@Autowired
	private DefaultSessionManager sessionManager;
	@Autowired
	private SysMessageDao  sysMessageDao; 
	
    private static final  Gson gson =  new Gson();
	
	@Bean//这个注解会从Spring容器拿出Bean
    public SpringWebSocketHandler infoHandler() {
        return new SpringWebSocketHandler();
    }
  
	public void pushByWebSocket(Message msg) {
		IMSession session = sessionManager.get(msg.getReceiver());
		//保存用户离线消息到数据库
		com.crm.sys.model.SysMessage ms = new com.crm.sys.model.SysMessage();
		
		 
		if (session != null && session.isConnected()) {
			ms.setIsread(1);
		    session.write(msg);
		}else{
			if(!msg.getSender().equals("system")){
				ms.setSenduser(Long.parseLong(msg.getSender().split("\\|")[0]));
				ms.setType(0); 
			}else{
				ms.setType(1); 
			}
			ms.setIsread(0);  
		}
		
		//保存消息 可以写下面
		//未发送
		try{
			  //系统或用户消息 保存到数据库     离线 上线消息不保存
			  if(msg.getType().equals("1")||msg.getType().equals("2")){
				    if(ms.getSenduser()==null){
				    	ms.setSenduser(1L); //设置默认发送人为机器人
				    }
					ms.setContent(msg.getContent());
					ms.setCreateuser(ms.getSenduser());
					ms.setReceiveuser(Long.parseLong(msg.getReceiver()));
					sysMessageDao.insertMessage(ms);
			  } 
		}catch(Exception e){
			log.warn(" Messages insert to database failure!!");
		} 
	}
	
	/**
     * 向用户发送消息
     * @param msg
     */
	public void push(Message msg) {
		IMSession session = sessionManager.get(msg.getReceiver());
		//保存用户离线消息到数据库
		com.crm.sys.model.SysMessage ms = new com.crm.sys.model.SysMessage();
		
		
		/*服务器集群时，可以在此 判断当前session是否连接于本台服务器，如果是，继续往下走，如果不是，将此消息发往当前session连接的服务器并 return
		if(!session.isLocalhost()){//判断当前session是否连接于本台服务器，如不是
			
			MessageDispatcher.execute(msg, session.getHost());
			return;
		}
		*/
		
		if (session != null && session.isConnected()) {
			
			ms.setIsread(1);
			/*//如果用户标示了DeviceToken 且 需要后台推送（Pushable=1） 说明这是ios设备需要使用anps发送
			
			if(StringUtil.isNotEmpty(session.getDeviceToken())&&session.getPushable()==User.PUSHABLE)
			{
				try {
					deliverByANPS(msg,session.getDeviceToken());
					msg.setStatus(Message.STATUS_SEND);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					msg.setStatus(Message.STATUS_NOT_SEND);
				}
			}else
			{
				
				//推送消息
				session.deliver(MessageUtil.transform(msg));
			}*/
			
			//推送消息
			
			  session.write(msg);
 			 
		}else{
			if(!msg.getSender().equals("system")){
				ms.setSenduser(Long.parseLong(msg.getSender().split("\\|")[0]));
				ms.setType(0); 
			}else{
				ms.setType(1); 
			}
			ms.setIsread(0);
			
			/*User target = ((UserService)ContextHolder.getBean("userServiceImpl")).getUserByAccount(msg.getReceiver());
			//如果用户标示了DeviceToken 且 需要后台推送（Pushable=1） 说明这是ios设备需要使用anps发送
			if(StringUtil.isNotEmpty(target.getDeviceToken())&&target.getPushable()==User.PUSHABLE)
			{
				try {
					deliverByANPS(msg,target.getDeviceToken());
					msg.setStatus(Message.STATUS_SEND);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					msg.setStatus(Message.STATUS_NOT_SEND);
				}
				
			} */
			
		}
		

		try{
			  Map<String, String> map = new HashMap<String, String>();
  		  //String myJson=   gson.toJson(message.getPayload());
			 // {content:message,type:1,receiver:recount},
     	      map.put("user", msg.getSender().split("\\|")[0]);
     	      map.put("file", msg.getFile());
     	      try{
     	    	 map.put("username",msg.getSender().split("\\|")[1]);
     	      }catch(Exception e){
     	    	 map.put("username","system");
     	      }
     	      map.put("type", msg.getType());
     	      map.put("content", msg.getContent());
     	      map.put("receiver", msg.getReceiver());
			  //手机端发送消息
			  infoHandler().sendMessageToUser(Long.parseLong(msg.getReceiver()), new TextMessage( gson.toJson(map)));
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		//保存消息 可以写下面
		//未发送
		try{
			  //系统或用户消息 保存到数据库     离线 上线消息不保存
			  if(msg.getType().equals("1")||msg.getType().equals("2")){
				    if(ms.getSenduser()==null){
				    	ms.setSenduser(1L); //设置默认发送人为机器人
				    }
					ms.setContent(msg.getContent());
					ms.setCreateuser(ms.getSenduser());
					ms.setReceiveuser(Long.parseLong(msg.getReceiver()));
					sysMessageDao.insertMessage(ms);
			  } 
			//((MessageService)ContextHolder.getBean("messageServiceImpl")).save(msg);
		}catch(Exception e){
			log.warn(" Messages insert to database failure!!");
		}
	
	}

	
/*	public void deliverByANPS(Message msg,String deviceToken) throws Exception {

		
		
		    String alert = getMessageTile(msg);
			// 被推送的iphone应用程序标示符
			PayLoad payLoad = new PayLoad();
			payLoad.addAlert(alert);
			payLoad.addBadge(1);
			payLoad.addSound("default");
			PushNotificationManager pushManager = PushNotificationManager.getInstance();
			pushManager.addDevice(deviceToken, deviceToken);
			String host = ConfigManager.getInstance().get("apple.anps.host"); // 测试用的苹果推送服务器
			int port = Integer.parseInt(ConfigManager.getInstance().get("apple.anps.port"));
			
			String password = ConfigManager.getInstance().get("apple.anps.p12.password");
            String p12File =  ConfigManager.getInstance().get("apple.anps.p12.file");
			pushManager.initializeConnection(host, port,this.getClass().getClassLoader().getResourceAsStream(p12File), password,
					SSLConnectionHelper.KEYSTORE_TYPE_PKCS12);

			// Send Push
			Device client = pushManager.getDevice(deviceToken);
			pushManager.sendNotification(client, payLoad); // 推送消息
			pushManager.stopConnection();
			pushManager.removeDevice(deviceToken);
 
	}
	
  
 */
}
